<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style></style>
  </head>
  <body>
    <div>Generator(生成器函数)异步方案(中)</div>
    <script>
      function ajax(url) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.responseText = "json";
          xhr.onload = function () {
            if (this.status === 200) {
              resolve(this.response);
            } else {
              reject(new Error(this.statusText));
            }
          };
          xhr.send();
        });
      }

      function* main() {
        const users = yield ajax("/asyn/user.json");
        console.log(users);
        const users2 = yield ajax("/asyn/user.json");
        console.log(users2);
      }
      const g = main();
      const result = g.next();
      //   if (result.done) return;
      console.log(result); //此时result是一个promise对象
      result.value.then((res) => {
        const result2 = g.next(res);
        if (result2.done) return;
        result2.value.then((res) => {
          g.next(res);
        });
      });
    </script>
  </body>
</html>
